<template>
	<view class="publish-page">
		<view class="form-container">
			<!-- 商家信息 -->
			<view class="merchant-info">
				<view class="merchant-row">
					<text class="merchant-label">商家名称：</text>
					<text class="merchant-name">{{ merchantInfo.name }}</text>
				</view>
				<view class="fee-balance-row">
					<text class="fee-info">通告费用：¥{{ merchantInfo.fee }}</text>
					<text class="balance-info">余额：¥{{ money.amount }}</text>
				</view>
			</view>

			<!-- 通告主题 -->
			<view class="form-row">
				<text class="form-label">通告主题：</text>
				<input v-model="formData.title" class="form-input" placeholder="请输入通告主题" />
			</view>

			<!-- 通告分类 -->
			<view class="form-row">
				<text class="form-label">通告分类：</text>
				<!-- 添加调试信息 -->
				<uni-data-select style="width: 80vw;font-size: 30rpx;" v-model="formData.topicCatalog" :localdata="categoryList"
					placeholder="请选择分类" :clear="false" @change="change"></uni-data-select>
			</view>

			<!-- 报名人数和人员限制 -->
			<view class="form-row">
				<text class="form-label">报名人数：</text>
				<text class="readonly-text">{{ merchantInfo.maxCount }}</text>
				<text class="unit-text">位</text>
			</view>
			<view class="form-row">
				<text class="form-label">人员限制：</text>
				<switch :checked="formData.genderLimit" @change="onGenderLimitChange" color="#AA0E99" style="transform: scale(0.8);" />
				<view class="limit-input-row">
						<text class="gender-text">女</text>
						<input v-model="formData.limitNum" class="gender-input" type="number" placeholder="0"
							:disabled="!formData.genderLimit" :max="merchantInfo.maxCount" @input="onLimitCountInput" />
						<text class="unit-text">人</text>
					</view>
			</view>

			<!-- 报名费用 -->
			<view class="form-row">
				<text class="form-label">报名费用：</text>
				<input v-model="formData.fee" class="form-input" type="digit" placeholder="请输入报名费用" />
			</view>

			<!-- 通告详情 -->
			<view class="form-row detail-row">
				<text class="form-label">通告详情：</text>
				<textarea v-model="formData.content" class="detail-textarea" placeholder="请详细描述活动内容、注意事项等..."
					maxlength="1000"></textarea>
			</view>
		</view>

		<!-- 底部发布按钮 -->
		<view class="bottom-bar">
			<button class="publish-btn" @click="publishTopic" :disabled="!canPublish">
				支付发布
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		computed,
		ref,
		watch
	} from 'vue'
	import {
		post
	} from '@/common/api.js'
	import {
		showDialog
	} from '@/common/util.js'
  import {
    one,
    useLoadList, useShowData
  } from "../../common/data";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		pay
	} from "../../common/api";

	const {
		listData: categoryList
	} = useLoadList("topic_catalog_list", {})

  const {data: money} = useShowData("my_money",{})


	// 商家信息
	const merchantInfo = ref({
		name: "",
		fee: '',
		balance: '1200',
		maxCount: 8 // 商家配置的报名人数
	})

	// 表单数据
	const formData = ref({
		title: '',
		topicCatalog: '', // 修改为catalog，与v-model保持一致
		genderLimit: false,
		limitNum: '', // 限制人数
		fee: '',
		content: ''
	})


	const categoryIndex = ref(0)
	const selectedCategory = ref(null)
	const selectedDate = ref('')


	onLoad(async (options) => {
		let res = await one("front_shop_view", options);
		if (res.code === 200) {
			merchantInfo.value = res.data;
		}
		if (options.date) {
			selectedDate.value = options.date
			console.log('接收到的时间参数:', selectedDate.value)
		}
	});

	// 计算是否可以发布
	const canPublish = computed(() => {
		return formData.value.title.trim() &&
			formData.value.fee &&
			formData.value.content.trim()
	})



	// 人员限制切换（适配 switch 组件）
	const onGenderLimitChange = (e) => {
		console.log('switch change:', e)
		formData.value.genderLimit = e.detail.value // switch 组件返回布尔值
		if (!e.detail.value) {
			formData.value.limitNum = ''
		}
	}

	// 限制人数输入
	const onLimitCountInput = (e) => {
		const value = parseInt(e.detail.value)
		if (value > merchantInfo.value.maxCount) {
			formData.value.limitNum = merchantInfo.value.maxCount+""
			uni.showToast({
				title: `限制人数不能超过${merchantInfo.value.maxCount}人`,
				icon: 'none',
				duration: 2000
			})
		} else if (value < 0) {
			formData.value.limitNum = '0'
		}
	}

	// 发布通告
	const publishTopic = async () => {
		if (!canPublish.value) {
			showDialog('请填写完整信息')
			return
		}

		// 检查人员限制设置
		if (formData.value.genderLimit) {
			const limitNum = parseInt(formData.value.limitNum)
			if (isNaN(limitNum) || limitNum <= 0) {
				showDialog('请输入有效的限制人数')
				return
			}
			if (limitNum > merchantInfo.value.maxCount) {
				showDialog(`限制人数不能超过报名总人数（${merchantInfo.value.maxCount}人）`)
				return
			}
		}

		// 检查余额是否足够
		if (parseFloat(merchantInfo.value.balance) < parseFloat(merchantInfo.value.fee)) {
			showDialog('余额不足，请先充值')
			return
		}

		// 弹出确认对话框
		uni.showModal({
			title: '确认发布',
			content: '是否确认布这条通告？',
			confirmText: '确认',
			cancelText: '取消',
			success: async (res) => {
				if (res.confirm) {
					// 用户点击确认，继续发布流程
					await doPublish()
				}
			}
		})
	}

	// 执行发布逻辑
	const doPublish = async () => {
		uni.showLoading({
			title: '发布中...'
		})

		try {
			const publishData = {
				...formData.value,
				payConfig: "ego",
				shop: merchantInfo.value.id
			}
			if (selectedDate.value) {
				publishData.beginDate = selectedDate.value
			}

			const res = await post('/topic/createExt', publishData)

			if (res.code === 200) {
				if (!res.data.needPay) {
					uni.showToast({
						title: '发布成功',
						icon: 'success'
					})
					uni.reLaunch({
						url: "/pages/index/index"
					})
					return;
				}

				// 			   { "appid": "wx499********7c70e",  // 应用ID（AppID）
				//   "partnerid": "148*****52",      // 商户号（PartnerID）
				//   "prepayid": "wx202254********************fbe90000", // 预支付交易会话ID
				//   "package": "Sign=WXPay",        // 固定值
				//   "noncestr": "c5sEwbaNPiXAF3iv", // 随机字符串
				//   "timestamp": 1597935292,        // 时间戳（单位：秒）
				//   "sign": "A842B45937F6EFF60DEC7A2EAA52D5A0" // 签名，这里用的 MD5 签名}

				pay(res.data.pay.pay, () => {
					uni.reLaunch({
						url: "/pages/index/index"
					})
				})

				// let pay = { ...res.data.pay.pay }
				// pay.package = "Sign=WXPay"
				// pay.timestamp = Number(pay.timestamp)

				// console.log(pay)

				// uni.requestPayment({
				// 	"provider": "wxpay",  //固定值为"wxpay"
				// 	"orderInfo": pay,
				// 	success: function (res) {
				// 		var rawdata = JSON.parse(res.rawdata);
				// 		console.log("支付成功");
				// 	},
				// 	fail: function (err) {
				// 		console.log('支付失败:' + JSON.stringify(err));
				// 	}
				// });


			} else {
				showDialog(res.msg || '发布失败，请重试')
			}
		} catch (error) {
			showDialog('发布失败，请重试')
		} finally {
			uni.hideLoading()
		}
	}


	const change = (e) => {
		console.log('uni-data-select change:', e)
		// 这里可以添加额外的处理逻辑
	}
</script>

<style scoped>
	.publish-page {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.form-container {
		padding: 20px;
	}

	.merchant-info {
		background-color: white;
		padding: 20px;
		margin-bottom: 20px;
		border-radius: 8px;
	}

	.merchant-row {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
	}

	.merchant-label {
		font-size: 16px;
		color: #333;
		margin-right: 10px;
	}

	.merchant-name {
		font-size: 16px;
		font-weight: 600;
		color: #333;
	}

	.fee-balance-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.fee-info,
	.balance-info {
		font-size: 16px;
		color: #333;
	}

	.form-row {
		background-color: white;
		padding: 4px 20px;
		margin-bottom: 1px;
		display: flex;
		align-items: center;
		min-height: 80rpx;
	}

	.form-row:first-child {
		border-top-left-radius: 8px;
		border-top-right-radius: 8px;
	}

	.form-row:last-child {
		border-bottom-left-radius: 8px;
		border-bottom-right-radius: 8px;
		margin-bottom: 20px;
	}

	.detail-row {
		align-items: flex-start;
		min-height: 120px;
	}

	.form-label {
		font-size: 16px;
		color: #333;
		margin-right: 10rpx;
		min-width: 80px;
	}

	.form-input {
		flex: 1;
		height: 40px;
		font-size: 16px;
		color: #333;
		background-color: transparent;
		border: none;
	}

	.number-input {
		width: 60px;
		height: 40px;
		font-size: 16px;
		color: #333;
		text-align: center;
		background-color: transparent;
		border: none;
	}

	.gender-input {
		width: 40px;
		height: 40px;
		font-size: 16px;
		color: #333;
		text-align: center;
		background-color: transparent;
		border: none;
	}

	.gender-input:disabled {
		color: #999;
	}

	.unit-text {
		font-size: 16px;
		color: #333;
		margin-left: 5px;
	}

	.gender-limit {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		margin-left: auto;
		gap: 10px;
	}

	.switch-container {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.limit-input-row {
		display: flex;
		align-items: center;
	}

	.readonly-text {
		font-size: 16px;
		color: #666;
		font-weight: 500;
	}

	.checkbox-label {
		display: flex;
		align-items: center;
		font-size: 16px;
		color: #333;
		margin-right: 15px;
	}

	.checkbox-text {
		margin-left: 8px;
		font-size: 16px;
		color: #333;
	}

	.gender-text {
		font-size: 16px;
		color: #333;
		margin-right: 10px;
	}

	.category-picker {
		flex: 1;
	}

	.picker-display {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 40px;
	}

	.picker-text {
		font-size: 16px;
		color: #333;
	}

	.picker-arrow {
		font-size: 12px;
		color: #999;
	}

	.detail-textarea {
		flex: 1;
		min-height: 80px;
		font-size: 16px;
		color: #333;
		background-color: transparent;
		border: none;
		line-height: 1.5;
		margin-top: 5px;
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: white;
		padding: 15px 20px;
		border-top: 1px solid #e0e0e0;
	}

	.publish-btn {
		width: 100%;
		height: 50px;
		background-color: #AA0E99;
		color: white;
		border: none;
		border-radius: 8px;
		font-size: 18px;
		font-weight: 600;
	}

	.publish-btn:disabled {
		background-color: #ccc;
	}

	.limit-tip {
		margin-top: 10px;
		padding: 10px;
		background-color: #f0f0f0;
		border-radius: 8px;
	}

	.tip-text {
		font-size: 16px;
		color: #333;
	}

	.debug-text {
		font-size: 12px;
		color: #999;
		margin-right: 10px;
	}
</style>
